#include <stdlib.h>
#include <stdio.h>
#include "tree.h"


extern char* fname;

node* createnode(char *text, struct token *tok, int nkids, ...)
{
	int i;		//counter variable
	va_list va;	// variable argument list variable

	// allocates space for the new node
	node *newnode = (node*) malloc(sizeof(node));

	// initializes all data types to "null ish values"
	newnode->numchild = 0;
	newnode->text = "\0";
	newnode->leaf = NULL;
	newnode->children = NULL;

	// initialize to passed in values
	if(text != NULL)       //if the text exists copy the text into the node
	{
		newnode->text = strdup(text);
	}

	newnode->numchild = nkids;
	newnode->leaf = tok;


	if(nkids > 0)	// if node has children
	{
		newnode->children = (node**) malloc(sizeof(node*) * nkids);
			// malloc room for the total number of kids

		va_start(va, nkids);	// start a variable arg list of length
					//.... nkids
			// for each kid make it equal to each object passed in
			// ... to the function (type node*)
		for(i = 0; i < nkids; i++)
		{
			newnode->children[i] = va_arg(va, node*);
		}
		va_end(va);	// end the var arg list
	}

	return newnode;		// return the newnode
}

void printT(node* head, int height)	// prints the tree
{
        printf("--------------------------------------------------------------------------------\n");
        printf("Parse Tree: %s\n", fname);
        printf("--------------------------------------------------------------------------------\n");

	printtree(head, height);
	printf("\n");
}

void printtree(node* head, int height)	// prints the tree
{
	int i;
	int nkids = head->numchild;
	char spacing[] = " ";

	if(head == NULL)
	{
		return;
	}

	// add the appropriate spacing before the current line
	for(i = 0; i < height; i++)
	{
		printf("%s", spacing);
	}

	//print out current node in tree

	if(head->leaf != NULL && nkids == 0)
	{
		printf("Child: %s: %d\n", head->leaf->text, head->leaf->category);

	}
	else
	{
		printf("%s: %d\n", head->text, head->numchild);
		// needs to be production rule name

	}


	//recursively call for each child
	for(i = 0; i < nkids; i++)
	{
		printtree(head->children[i], height + 1);
			// calls the func for the next kid and 
	}
}
